package com.warm.gen.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.convert.Convert;
import com.warm.core.domain.R;
import com.warm.core.page.BaseController;
import com.warm.core.page.TableDataInfo;
import com.warm.gen.service.IGenTableColumnService;
import com.warm.gen.service.IGenTableService;
import com.warm.log.annotation.Log;
import com.warm.log.enums.BusinessType;
import com.warm.orm.domain.gen.GenTable;
import com.warm.orm.domain.gen.GenTableColumn;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.DownloadedFile;
import org.noear.solon.validation.annotation.Valid;
import org.noear.solon.validation.annotation.Validated;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成 操作处理
 *
 * @author warm
 */
@SaIgnore
@Valid
@Controller
@Mapping("/tool/gen")
public class GenController extends BaseController {
    @Inject
    private IGenTableService genTableService;

    @Inject
    private IGenTableColumnService genTableColumnService;

    /**
     * 查询代码生成列表
     */
    @SaCheckPermission("tool:gen:list")
    @Get
    @Mapping("/list")
    public TableDataInfo<GenTable> genList(GenTable genTable) {
        return genTableService.selectGenTablePage(genTable);
    }

    /**
     * 修改代码生成业务
     */
    @SaCheckPermission("tool:gen:query")
    @Get
    @Mapping(value = "/{tableId}")
    public R<Map<String, Object>> getInfo(Long tableId) {
        GenTable table = genTableService.selectGenTableById(tableId);
        List<GenTable> tables = genTableService.selectGenTableAll();
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("info", table);
        map.put("rows", list);
        map.put("tables", tables);
        return R.ok(map);
    }

    /**
     * 查询数据库列表
     */
    @SaCheckPermission("tool:gen:list")
    @Get
    @Mapping("/db/list")
    public TableDataInfo<GenTable> dataList(GenTable genTable) {
        return genTableService.selectDbTableList(genTable);
    }

    /**
     * 查询数据表字段列表
     */
    @SaCheckPermission("tool:gen:list")
    @Get
    @Mapping(value = "/column/{tableId}")
    public TableDataInfo columnList(Long tableId) {
        TableDataInfo dataInfo = new TableDataInfo();
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        dataInfo.setRows(list);
        dataInfo.setTotal(list.size());
        return dataInfo;
    }

    /**
     * 导入表结构（保存）
     */
    @SaCheckPermission("tool:gen:import")
    @Log(title = "代码生成", businessType = BusinessType.IMPORT)
    @Post
    @Mapping("/importTable")
    public R<Void> importTableSave(String tables) {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);
        return R.ok();
    }

    /**
     * 修改保存代码生成业务
     */
    @SaCheckPermission("tool:gen:edit")
    @Log(title = "代码生成", businessType = BusinessType.UPDATE)
    @Put
    @Mapping
    public R<Void> editSave(@Validated GenTable genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return R.ok();
    }

    /**
     * 删除代码生成
     */
    @SaCheckPermission("tool:gen:remove")
    @Log(title = "代码生成", businessType = BusinessType.DELETE)
    @Delete
    @Mapping("/{tableIds}")
    public R<Void> remove(Long[] tableIds) {
        genTableService.deleteGenTableByIds(tableIds);
        return R.ok();
    }

    /**
     * 预览代码
     */
    @SaCheckPermission("tool:gen:preview")
    @Get
    @Mapping("/preview/{tableId}")
    public R<Map<String, String>> preview(Long tableId) throws IOException {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return R.ok(dataMap);
    }

    /**
     * 生成代码（下载方式）
     */
    @SaCheckPermission("tool:gen:code")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @Get
    @Mapping("/download/{tableName}")
    public void download(Context ctx, String tableName) throws IOException {
        byte[] data = genTableService.downloadCode(tableName);
        genCode(ctx, data);
    }

    /**
     * 生成代码（自定义路径）
     */
    @SaCheckPermission("tool:gen:code")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @Get
    @Mapping("/genCode/{tableName}")
    public R<Void> genCode(String tableName) {
        genTableService.generatorCode(tableName);
        return R.ok();
    }

    /**
     * 同步数据库
     */
    @SaCheckPermission("tool:gen:edit")
    @Log(title = "代码生成", businessType = BusinessType.UPDATE)
    @Get
    @Mapping("/synchDb/{tableName}")
    public R<Void> synchDb(String tableName) {
        genTableService.synchDb(tableName);
        return R.ok();
    }

    /**
     * 批量生成代码
     */
    @SaCheckPermission("tool:gen:code")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @Get
    @Mapping("/batchGenCode")
    public void batchGenCode(Context ctx, String tables) throws IOException {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = genTableService.downloadCode(tableNames);
        logger.info("下载成功！");
        genCode(ctx, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(Context ctx, byte[] data) throws IOException {
        InputStream stream = new ByteArrayInputStream(data);
        DownloadedFile file = new DownloadedFile("application/octet-stream", stream, "warm.zip");
        ctx.outputAsFile(file);
    }
}
